package com.leonzx.base.controller.userpermission;

import com.leonzx.base.config.pager.Page;
import com.leonzx.base.config.pager.PageInfo;
import com.leonzx.base.controller.base.BaseController;
import com.leonzx.base.entity.system.*;
import com.leonzx.base.service.system.*;
import com.leonzx.base.utils.Constants;
import com.leonzx.base.utils.CronDateUtils;
import com.leonzx.base.utils.PermissionUtils;
import com.leonzx.base.utils.UUIDUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author:张勇
 * @Description:
 * @Date: 2018-06-11 9:27
 */
@RestController
@RequestMapping("/ajax/role")
public class AjaxRoleController extends BaseController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private UserRoleTempService userRoleTempService;
    @Autowired
    private MenuRoleService menuRoleService;
    @Autowired
    private JobService jobService;

    /**
     * 角色列表
     *
     * @param baseRole
     * @param page
     * @return
     */
    @RequestMapping("/list")
    @RequiresPermissions("/role/torolelist")
    public Map<String, Object> list(Role baseRole, @PageInfo(pageSize = Page.PAGE_SIZE, orderBy = "create_time") Page<Role> page) {
        Map<String, Object> result = getMap();
        try {
            List<Role> baseRoles = roleService.getAllBaseRole(baseRole);
            page.setResult(baseRoles);
            SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
            //循环list，处理数据
            for (Role b : baseRoles) {
                String createTimeStr = "";
                if (b.getCreateTime() != null) {
                    createTimeStr = sdf.format(b.getCreateTime());
                }
                String createUserName = userService.getUserNameById(b.getCreateUserId());
                b.setCreateTimeStr(createTimeStr);
                b.setCreateUserName(createUserName);
            }
            result.put("count", page.getTotalCount());
            result.put("data", baseRoles);
            result.put("code", "0");
            result.put("msg", "加载完成");
        } catch (Exception e) {
            logger.error("获取用户数据失败", e);
            addFailMessage(result, "获取用户数据失败");
        }
        return result;
    }

    /**
     * 添加角色
     */
    @RequestMapping("/saverole")
    @RequiresPermissions("/role/torolelist")
    public Map<String, Object> saveorupdate(Role role) {
        Map<String, Object> result = getMap();
        try {
            if (StringUtils.isNotBlank(role.getId())) {
                roleService.saveOrUpdate(role);
                addSuccessMessage(result, "角色更新成功");

            } else {
                role.setName(role.getName());
                List<Role> baseRoles = roleService.getAllBaseRole(role);
                if (baseRoles.size() > 0) {
                    addFailMessage(result, "角色已存在");
                } else {
                    role.setCreateUserId(currentUser().getId());
                    roleService.saveOrUpdate(role);
                    addSuccessMessage(result, "保存角色成功");
                }
            }
        } catch (Exception e) {
            logger.error("保存角色失败", e);
            addFailMessage(result, "保存角色失败，请联系管理员");
        }
        return result;
    }

    /**
     * 禁用角色
     *
     * @param role
     * @return
     */
    @RequestMapping("/del")
    @RequiresPermissions("/role/torolelist")
    public Map<String, Object> delRole(Role role) {
        Map<String, Object> result = getMap();
        try {
            role.setState(Constants.STATE_INVAILD);
            roleService.saveOrUpdate(role);
            addSuccessMessage(result, "角色禁用成功");
        } catch (Exception e) {
            logger.error("禁用角色失败", e);
            addFailMessage(result, "禁用角色失败，联系管理员");
        }
        return result;
    }

    /**
     * 角色启用
     *
     * @param role
     * @return
     */
    @RequestMapping("/recover")
    public Map<String, Object> recover(Role role) {
        Map<String, Object> result = getMap();
        try {
            role.setState(Constants.STATE_VAILD);
            roleService.saveOrUpdate(role);
            addSuccessMessage(result, "启用角色成功");
        } catch (Exception e) {
            logger.error("启用角色失败", e);
            addFailMessage(result, "启用角色失败， 联系管理员");
        }
        return result;
    }

    /**
     * 人员分配角色,正式和临时
     *
     * @param userId
     * @return
     */
    @RequestMapping("/chooserole")
    @RequiresPermissions("/userpermission/user/list")
    public Map<String, Object> chooserole(String userId, String roleId, Integer isTemp, Date expireTime,Boolean state) {
        Map<String, Object> result = getMap();
        try {
            Integer statInt = 0;
            if (state == true){
                statInt = 1;
            }
            if (isTemp == 1) {//isTemp，代表保存临时人员-角色表
                    UserRoleTemp userRoleTemp = new UserRoleTemp();
                    userRoleTemp.setCreateUserId(currentUser().getId());
                    userRoleTemp.setUserId(userId);
                    userRoleTemp.setState(statInt);
                    userRoleTemp.setRoleId(roleId);
                    userRoleTemp.setExpireTime(expireTime);
                    userRoleTempService.saveOrUpdate(userRoleTemp);
                    //创建一个定时任务，到时间清相关缓存
                    String jobName ="com.leonzx.base.config.quartz.job.UserReflash";
                    String jobClassName = "com.leonzx.base.config.quartz.job.UserReflash";//路径
                    String jobGroupName = UUIDUtils.getUUID();//分组，路径相同 不能重复
                    String description = "人员临时角色超时清缓存";//描述
                    String cronExpression = CronDateUtils.getCron(expireTime);
                    Map<String, String> datas = new HashMap<>();
                    User user = userService.getUserById(userId);
                    String userJson = gson.toJson(user);
                    datas.put("user",userJson);
                    jobService.jobAdd(jobName,jobClassName,jobGroupName,description,cronExpression,datas);
            } else {
                //关联所有当前选择角色
                    UserRole userRole = new UserRole();
                    userRole.setUserId(userId);
                    userRole.setRoleId(roleId);
                    userRole.setCreateUserId(currentUser().getId());
                    userRole.setState(statInt);
                    userRoleService.saveOrUpdate(userRole);
                    //清理缓存，根据userName
                    User user =  userService.getUserById(userId);
                    PermissionUtils.reflashPermission(user);
            }
            addSuccessMessage(result, "操作成功");
        } catch (Exception e) {
            logger.error("人员分配角色失败", e);
            addFailMessage(result, "分配失败，请联系管理员");

        }
        return result;
    }

    /**
     * 人员分配角色，显示所有角色
     *
     * @param baseRole
     * @param page
     * @return
     */
    @RequestMapping("/chooselist")
    @RequiresPermissions("/userpermission/user/list")
    public Map<String, Object> list(String userId1, Role baseRole, @PageInfo(pageSize = Page.PAGE_SIZE, orderBy = "create_time") Page<Role> page) {
        Map<String, Object> result = getMap();
        try {
            baseRole.setState(Constants.STATE_VAILD);
            List<Role> baseRoles  = roleService.getAllBaseRole(baseRole);
            page.setResult(baseRoles);
            result.put("count", page.getTotalCount());
            result.put("data", baseRoles);
            result.put("code", "0");
            result.put("msg", "加载完成");
        } catch (Exception e) {
            logger.error("获取用户数据失败", e);
            addFailMessage(result, "获取用户数据失败");
        }
        return result;
    }

    /**
     * 人员分配临时角色,只显示我有他没有的
     *      *
     * @param
     * @param page
     * @return
     */
    @RequestMapping("/chooselisttemp")
    @RequiresPermissions("/userpermission/user/list")
    public Map<String, Object> chooselisttemp(String userId1, Role role, @PageInfo(pageSize = Page.PAGE_SIZE, orderBy = "br.create_time") Page<Role> page) {
        Map<String, Object> result = getMap();
        try {
            String name = role.getName();
            List<Role> baseRoles = roleService.getMyRolesOutHis(currentUser().getId(),userId1,name);
            page.setResult(baseRoles);
            if (baseRoles.size()==0){
                addSuccessMessage(result,"没有可分配的临时权限");
            }else{
                result.put("code", "0");
                result.put("msg", "加载完成");
            }
            result.put("count", page.getTotalCount());
            result.put("data", baseRoles);
        } catch (Exception e) {
            logger.error("获取用户数据失败", e);
            addFailMessage(result, "获取用户数据失败");
        }
        return result;
    }

    /**
     * 角色分配权限保存
     *
     * @param roleId
     * @param menuIds
     * @return
     */
    @RequestMapping("/rolemenusave")
    @RequiresPermissions("/userpermission/user/list")
    public Map<String, Object> rolemenusave(String roleId, String menuIds) {
        Map<String, Object> result = getMap();
        try {
            String[] menuId = menuIds.split(",");
            menuRoleService.delAllByRoleId(roleId);
            for (int i = 0; i < menuId.length; i++) {
                MenuRole menuRole = new MenuRole();
                menuRole.setMenuId(menuId[i]);
                menuRole.setRoleId(roleId);
                menuRole.setCreateUserId(currentUser().getId());
                menuRole.setState(Constants.STATE_VAILD);
                menuRoleService.saveOrUpdate(menuRole);
                addSuccessMessage(result, "角色分配权限成功");
                //清楚所有拥有这个角色的人员缓存
                UserRole userRole = new UserRole();
                userRole.setRoleId(roleId);
               List <UserRole> userRoles = userRoleService.findByUserIdAndRoleIdAndState(userRole);
               if (!Objects.isNull(userRoles)){
                   for (UserRole ur:userRoles){
                       String userId = ur.getUserId();
                       if (!Objects.isNull(userService.getUserById(userId))){
                           User user =  userService.getUserById(userId);
                           PermissionUtils.reflashPermission(user);
                       }
                   }
               }
            }
        } catch (Exception e) {
            logger.error("角色分配权限失败", e);
            addFailMessage(result, "角色分配权限失败");
        }
        return result;
    }

}
